package com.wodsy.phoenix.scaffold;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.HashMap;

/**
 * Created by zcwc on 2015/3/19.
 */
public class Scaffold {


    private static Configuration cfg;

    static {
        //初始化FreeMarker配置
        //创建一个Configuration实例
        cfg = new Configuration(Configuration.VERSION_2_3_21);
        //设置FreeMarker的模版文件位置

        try {
            cfg.setDirectoryForTemplateLoading(new File(new Scaffold().getClass().getResource("/").getPath()+"/"));
            cfg.setDefaultEncoding("UTF-8");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public static void main(String[] args) {

        //哪个模块的
        //POJO类名
        //SERVICE类名
        //DAO类名前缀

        String moduleName = "userc"; //模块名称
        String pojoClassName = "UserBasic";
        String pojoClassIDType="Integer"; //Integer或者Long
        String daoClassPrefix = "UserManagement";//dao类前缀
        String daoRepositoryName =  daoClassPrefix.substring(0, 1).toLowerCase()+daoClassPrefix.replaceFirst("\\w","");//默认为daoClassPrefix首字母小写
        String serviceClassPrefix="UserManagement";//service类前缀


        System.out.printf(daoRepositoryName);

        HashMap<Object, Object> hs = new HashMap<>();


        //建立数据模型
        HashMap root = new HashMap();
        //放入对应数据key value
        root.put("moduleName", moduleName);
        root.put("pojoClassName",pojoClassName);
        root.put("pojoClassIDType",pojoClassIDType);
        root.put("daoClassPrefix",daoClassPrefix);
        root.put("serviceClassPrefix",serviceClassPrefix);
        root.put("daoRepositoryName",daoRepositoryName);



        generateSourceFileFromTemplate("dao.ftl",daoClassPrefix+"Dao",root);
        generateSourceFileFromTemplate("daoimpl.ftl", daoClassPrefix + "DaoImpl", root);
        generateSourceFileFromTemplate("service.ftl",serviceClassPrefix+"Service",root);
        generateSourceFileFromTemplate("serviceimpl.ftl",serviceClassPrefix+"ServiceImpl",root);

    }


    public static void generateSourceFileFromTemplate(String templateFileName,String generateFileName,HashMap root){
        //取得模版文件
        Template t = null;
        try {
            t = cfg.getTemplate(templateFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //合并数据模型和模版，并将结果输出到out中
        try {

            Writer out = new OutputStreamWriter(new FileOutputStream(new File(new Scaffold().getClass().getResource("/").getPath()+"/"+generateFileName+".java")));


            t.process(root, out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }

    }



}
